package zydhsms

import (
	"encoding/xml"
	"fmt"
	"github.com/spf13/viper"
	"go-shop-api/pkg/e"
	"go-shop-api/pkg/zydhlog"
	"io"
	"math/rand"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

type SmsXml struct {
	Returnstatus  string `xml:"returnstatus"`
	Message       string `xml:"message"`
	Remainpoint   string `xml:"remainpoint"`
	TaskID        string `xml:"taskID"`
	SuccessCounts string `xml:"successCounts"`
}

// SendSms 发送验证码  *serializer.Response
func SendSms(phone, content string) {
	//用户账号 $account
	account := viper.Get("sms.account").(string) //conf.AppConf.SmsConf.Account
	//用户密码 $password
	password := viper.Get("sms.password").(string) //conf.AppConf.SmsConf.Password
	//请求地址 "http://sh2.ipyy.com/sms.aspx?action=send";
	host := viper.Get("sms.host").(string) //conf.AppConf.SmsConf.Host
	//企业ID $userid [可忽略]
	userid := viper.Get("sms.userid").(string) // strconv.Itoa(conf.AppConf.SmsConf.Userid)

	apiUrl := host
	// URL param
	data := url.Values{}
	data.Set("userid", userid)
	data.Set("account", account)
	data.Set("password", password)
	data.Set("mobile", phone)
	data.Set("content", content)
	data.Set("sendTime", "")

	//组装
	u, err := url.ParseRequestURI(apiUrl)
	if err != nil {
		//写入日志
		zydhlog.Error("parse url requestUrl failed, err:" + err.Error())
		return
		//fmt.Printf("parse url requestUrl failed, err:%v\n", err)
		//return serializer.NewResponse(e.Error, "parse url requestUrl failed, err:"+err.Error(), e.TipsGeneral, nil)
	}

	// URL encode
	u.RawQuery = data.Encode()
	fmt.Println(u.String())
	//http://127.0.0.1:9090/get_param?age=18&name=%E5%B0%8F%E7%8E%8B%E5%AD%90

	//发送
	resp, err := http.Get(u.String())
	if err != nil {
		zydhlog.Error("parse url request Url failed, err:" + err.Error())
		return
		//return serializer.NewResponse(e.Error, "parse url request Url failed, err:"+err.Error(), e.TipsGeneral, nil)
	}
	//关闭
	defer resp.Body.Close() //一定要关闭，不然一直占用

	//读取server返回的内容
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		zydhlog.Error("get resp failed, err:" + err.Error())
		return
		//return serializer.NewResponse(e.Error, "get resp failed, err:"+err.Error(), e.TipsGeneral, nil)
	}
	fmt.Println(string(b))

	//$result = file_get_contents($gateway);
	//$xml = json_decode( json_encode( simplexml_load_string( $result ) ), true );
	//$xml['returnstatus'] = strtolower( $xml['returnstatus'] );

	// 返回数组结构
	// 返回状态 [returnstatus] => Faild
	// 返回信息 [message] => 密码错了
	// 返回余额 [remainpoint] => 0
	// 返回本次任务ID [taskID] => 0
	// 返回成功短信数 [successCounts] => 0
	//return $xml;

	////将文件读取成字节数组
	//content, err := ioutil.ReadFile("per.xml")
	//if err != nil {
	//	fmt.Fprintln(os.Stderr, err.Error())
	//	os.Exit(9)
	//}

	var sx SmsXml
	//反序列化xml
	err = xml.Unmarshal(b, &sx)
	if err != nil {
		zydhlog.Error("xml Unmarshal failed, err:" + err.Error())
		return
		//return serializer.NewResponse(e.Error, "xml Unmarshal failed, err:"+err.Error(), e.TipsGeneral, nil)
	}

	if sx.Returnstatus == "Faild" {
		zydhlog.Error("xml Unmarshal failed, err:" + sx.Message)
		return
		//return serializer.NewResponse(e.Error, sx.Message, e.TipsGeneral, nil)
	}

	//return serializer.NewResponse(e.Success, e.TipsOk, e.TipsSuccessSendSmsCode, map[string]interface{}{
	//	"return_xml":     string(b),
	//	"sms_xml_struct": sx,
	//})
	zydhlog.Info("send sms ok, " + e.TipsSuccessSendSmsCode)

	//发送短信成功后操作
	//	//写入redis缓存
	//	go redis.SetKey("ss.Phone",encrypt(code))
	//	//写入sms发送日志表 - 看需求
	//	go writeSmsSendLog( scene:  phone  encrypt(code) )

}

///*
//YunTongXun_Send_Template_SMS
//* +-------------------------------------------------
//* + 云通讯短信接口
//* +-------------------------------------------------
//* + @param string $phone 手机号码
//* + @param array $data $data[0]短信验证码 | data[1]时间限制
//* + @param int $tempId 短信模版编号
//* +-------------------------------------------------
//* + @return boolean true|false
//* +-------------------------------------------------
//*/
//func YunTongXun_Send_Template_SMS( $phone, $data ,$config) {
//
//$userid = '';
//
//$account = $config['sms_account'];
//
//$password = $config['sms_password'];
//
////发送到的目标手机号码 $mobile
//$mobile = $phone;
//
////短信内容 $content
//$content = "您的验证码是：". $data[0] ."。请不要把验证码泄漏给其他人。如非本人操作，可不用理会！【万奈庭】";
//
//$gateway = "http://sh2.ipyy.com/sms.aspx?action=send";
//$gateway .= "&userid={$userid}";
//$gateway .= "&account={$account}";
//$gateway .= "&password={$password}";
//$gateway .= "&mobile={$mobile}";
//$gateway .= "&content={$content}";
//$gateway .= "&sendTime=";
//$result = file_get_contents($gateway);
//$xml = json_decode( json_encode( simplexml_load_string( $result ) ), true );
////$xml['returnstatus'] = strtolower( $xml['returnstatus'] );
//
//// 返回数组结构
//// 返回状态 [returnstatus] => Faild
//// 返回信息 [message] => 密码错了
//// 返回余额 [remainpoint] => 0
//// 返回本次任务ID [taskID] => 0
//// 返回成功短信数 [successCounts] => 0
//return $xml;
//}

// GetSmsCode 生成验证码，随机生成几位数字
func GetSmsCode(num int) string {
	// 我们一般使用系统时间的不确定性来进行初始化
	//rand.Intn(10) 生成 [0,n)区间的一个随机数（注意：不包括n）
	code := ""
	rand.Seed(time.Now().Unix())
	for i := 0; i < num; i++ {
		code = code + strconv.Itoa(rand.Intn(10))
	}
	return code
}
